import React from 'react'
import {
  Form,
  Input,
  Select,
  Button,
  Table,
  Divider,
  Pagination,
  Modal,
  Radio,
  Popconfirm,
  message
} from 'antd'
import { connect } from 'react-redux'
import _ from 'lodash'
import {
  productConnectSmbApi,
  tuserConnectTcpApi,
  tuserAddApi,
  tuserFindBypageApi,
  tuserDelApi,
  tuserUpdateApi,
  tuserGetPrincipal,
  tuserCheckName
} from '../api/ajax'

const FormItem = Form.Item
const Option = Select.Option
const RadioGroup = Radio.Group
const { TextArea } = Input
class UserManage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      totalRecord: 0,
      tableSource: [],
      currentPage: 1,
      pageNum: 1,
      pageSize: 5,
      visible: false,
      confirmLoading: false,
      pushType: 1,
      userName: '',
      principal: '',
      pushTypeSearch: '',
      address: '',
      isPassLinkTest: false,
      isEdit: false,
      isFirstTest: false,
      selectData: [],
      Testing: false
    }
  }
  componentDidMount() {
    this.loadData()
  }
  loadData = (pageNum = 1) => {
    const {
      pageSize,
      userName,
      principal,
      pushTypeSearch,
      address
    } = this.state
    this.setState({ currentPage: pageNum, pageNum })
    tuserFindBypageApi({
      pageNum,
      pageSize,
      userName,
      principal,
      pushType: pushTypeSearch * 1,
      address
    }).then(v => {
      const {
        list: { totalRecord, results }
      } = v
      _.each(results, v => {
        v.key = v.id
      })
      this.setState({
        totalRecord,
        tableSource: results ? results : []
      })
    })

    tuserGetPrincipal().then(v => {
      this.setState({
        selectData: _.concat([{ principal: '' }], v)
      })
    })
  }

  render() {
    const {
      getFieldDecorator,
      resetFields,
      setFields,
      setFieldsValue,
      validateFields,
      getFieldsValue
    } = this.props.form
    const rules = {
      rules: [
        {
          required: true,
          message: '字符不得为空'
        }
      ]
    }
    const {
      visible,
      confirmLoading,
      pushType,
      isPassLinkTest,
      userName,
      principal,
      pushTypeSearch,
      address,
      tableSource,
      totalRecord,
      pageSize,
      currentPage,
      isEdit,
      selectId,
      isFirstTest,
      selectData,
      Testing
    } = this.state
    const formItemLayout = {
      labelCol: {
        xs: { span: 6 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    }
    let testResult = ''
    let testColor = isPassLinkTest ? 'green' : 'red'
    if (isFirstTest) {
      testResult = isPassLinkTest ? '连接成功' : '连接失败'
    } else {
      testResult = ''
    }
    const options = selectData.map((d, k) => (
      <Option key={k} value={d.principal}>
        {d.principal}
      </Option>
    ))
    return (
      <div className="home">
        <div className="home-head">
          <Form layout="inline">
            <FormItem label="目标名称">
              <Input
                value={userName}
                onChange={e => this.setState({ userName: e.target.value })}
              />
            </FormItem>
            <FormItem label="负责人">
              <Input
                value={principal}
                onChange={e => this.setState({ principal: e.target.value })}
              />
            </FormItem>
            <FormItem label="方式">
              <Select
                showSearch
                placeholder="请选择"
                style={{ width: 170 }}
                value={pushTypeSearch}
                onChange={e => this.setState({ pushTypeSearch: e })}
              >
                <Option value={1}>同步</Option>
                <Option value={2}>FTP</Option>
              </Select>
            </FormItem>
            <FormItem label="源地址">
              <Input
                value={address}
                onChange={e => this.setState({ address: e.target.value })}
              />
            </FormItem>
            <Button
              type="primary"
              style={{ marginRight: '10px' }}
              onClick={() => this.loadData()}
            >
              查询
            </Button>
            <Button
              onClick={() => {
                this.setState(
                  {
                    userName: '',
                    principal: '',
                    pushTypeSearch: '',
                    address: ''
                  },
                  () => this.loadData(1)
                )
              }}
            >
              重置
            </Button>
          </Form>
        </div>
        <div className="home-body">
          <div className="home-body-head">
            <h3 className="home-body-head-title">目标列表</h3>
            <Button
              type="primary"
              onClick={() =>
                this.setState({
                  visible: true,
                  isEdit: false,
                  isPassLinkTest: false,
                  Testing: false
                })
              }
            >
              添加新目标
            </Button>
          </div>
          <Table
            dataSource={tableSource}
            scroll={{ x: 1200 }}
            columns={[
              {
                title: '目标名称',
                dataIndex: 'userName'
              },
              {
                title: '描述',
                dataIndex: 'discretion'
              },
              {
                title: '推送方式',
                dataIndex: 'pushType',
                render: (text, record) => (
                  <span>{text === 1 ? '同步' : 'FTP'} </span>
                )
              },
              {
                title: '地址',
                dataIndex: 'address'
              },
              {
                title: '服务器用户名',
                dataIndex: 'serverName'
              },
              {
                title: '负责人',
                dataIndex: 'principal'
              },
              {
                title: '负责人联系方式',
                dataIndex: 'phone'
              },
              {
                title: '操作',
                render: (text, record) => (
                  <span>
                    <button
                      className="button-a"
                      onClick={() => {
                        const {
                          id,
                          userName,
                          discretion,
                          serverName,
                          serverPassword,
                          pushType,
                          address,
                          principal,
                          phone,
                          port
                        } = record

                        this.setState(
                          {
                            visible: true,
                            confirmLoading: false,
                            isEdit: true,
                            isPassLinkTest: false,
                            selectId: id,
                            pushType,
                            isFirstTest: false,
                            Testing: false
                          },
                          () =>
                            setFieldsValue({
                              discretion,
                              serverName,
                              userName,
                              serverPassword,
                              pushType,
                              address,
                              principal,
                              phone,
                              port
                            })
                        )
                      }}
                    >
                      编辑
                    </button>
                    <Divider type="vertical" />
                    <Popconfirm
                      title="是否删除此条记录"
                      onConfirm={() => {
                        const { id } = record
                        tuserDelApi({ id }).then(v => {
                          message.success('删除成功')
                          this.loadData()
                        })
                      }}
                      onCancel={() => {}}
                      okText="是"
                      cancelText="否"
                    >
                      <button className="button-a">删除</button>
                    </Popconfirm>
                  </span>
                )
              }
            ]}
            pagination={false}
          />
          <div className="home-body-page">
            <Pagination
              total={totalRecord}
              pageSize={pageSize}
              current={currentPage}
              onChange={pageNum => {
                this.setState({ pageNum, currentPage: pageNum })
                this.loadData(pageNum)
              }}
              showTotal={total => `共${total}条数据`}
            />
          </div>
        </div>
        <Modal
          title={isEdit ? '编辑' : '新增'}
          visible={visible}
          onOk={() => {
            if (!isPassLinkTest) {
              message.warning('请先检测服务器连接')
              return
            }
            validateFields((errors, values) => {
              if (errors) return
              this.setState({ confirmLoading: true })
              if (isEdit) {
                values.id = selectId
                tuserUpdateApi(values).then(v => {
                  message.success('修改成功')
                  resetFields()
                  this.setState({
                    visible: false,
                    confirmLoading: false,
                    isFirstTest: false
                  })
                  this.loadData()
                })
              } else {
                tuserAddApi(values).then(v => {
                  message.success('新增成功')
                  resetFields()
                  this.setState({
                    visible: false,
                    confirmLoading: false,
                    isFirstTest: false
                  })
                  this.loadData()
                })
              }
            })
          }}
          confirmLoading={confirmLoading}
          onCancel={() => {
            resetFields()
            this.setState({
              visible: false,
              confirmLoading: false,
              isFirstTest: false
            })
          }}
        >
          <Form>
            <FormItem label="目标名称" {...formItemLayout}>
              {getFieldDecorator('userName', rules)(
                <Input
                  autoComplete="off"
                  onBlur={v => {
                    const value = v.target.value
                    tuserCheckName({ name: value }).then(data => {
                      if (data) {
                        setFields({
                          userName: {
                            value: value,
                            errors: [new Error('用户名重复')]
                          }
                        })
                      }
                    })
                  }}
                />
              )}
            </FormItem>
            <FormItem label="描述" {...formItemLayout}>
              {getFieldDecorator('discretion')(<TextArea type="text" />)}
            </FormItem>
            <FormItem label="传输方式" {...formItemLayout}>
              {getFieldDecorator('pushType', rules)(
                <RadioGroup
                  onChange={e => {
                    this.setState({ pushType: e.target.value })
                  }}
                >
                  <Radio value={1}>同步</Radio>
                  <Radio value={2}>FTP</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <div>
              服务器地址填写示例: 192.168.0.13/test/name/ (/test/name为文件夹)
            </div>
            <FormItem label="目标地址" {...formItemLayout}>
              {getFieldDecorator('address', rules)(<Input />)}
            </FormItem>
            {pushType === 2 && (
              <FormItem label="端口" {...formItemLayout}>
                {getFieldDecorator('port', rules)(<Input />)}
              </FormItem>
            )}
            <FormItem label="服务器用户名" {...formItemLayout}>
              {getFieldDecorator('serverName', rules)(<Input />)}
            </FormItem>
            <FormItem label="服务器密码" {...formItemLayout}>
              {getFieldDecorator('serverPassword', rules)(
                <Input type="password" autoComplete="off" />
              )}
            </FormItem>
            <FormItem label="负责人" {...formItemLayout}>
              {getFieldDecorator('principal', rules)(
                <Select
                  showSearch
                  onSearch={v => {
                    selectData[0] = {
                      principal: v
                    }
                    this.setState({ selectData })
                  }}
                  onChange={v => {
                    const selectItem = _.find(selectData, { principal: v })
                    setFieldsValue({ phone: selectItem.phone })
                  }}
                >
                  {options}
                </Select>
              )}
            </FormItem>
            <FormItem label="负责人联系方式" {...formItemLayout}>
              {getFieldDecorator('phone', {
                rules: [
                  {
                    whitespace: true,
                    pattern: '^[1][3,4,5,7,8][0-9]{9}$',
                    message: '请输入正确的联系方式!'
                  }
                ]
              })(<Input />)}
            </FormItem>
            <div style={{ textAlign: 'right', padding: '0 40px' }}>
              <span style={{ marginRight: '30px', color: testColor }}>
                {testResult}
              </span>
              <Button
                type="primary"
                loading={Testing}
                disabled={Testing}
                onClick={() => {
                  this.setState({ Testing: true })
                  if (pushType === 1) {
                    let tcpData = getFieldsValue([
                      'address',
                      'serverName',
                      'serverPassword'
                    ])

                    productConnectSmbApi({
                      sourceAddress: tcpData.address,
                      userName: tcpData.serverName,
                      password: tcpData.serverPassword
                    })
                      .then(isPassLinkTest => {
                        this.setState({
                          isPassLinkTest,
                          isFirstTest: true,
                          Testing: false
                        })
                      })
                      .catch(() => {
                        this.setState({ Testing: false })
                      })
                  } else {
                    let tcpData = getFieldsValue([
                      'address',
                      'serverName',
                      'serverPassword',
                      'port'
                    ])
                    tuserConnectTcpApi({
                      address: tcpData.address,
                      serverName: tcpData.serverName,
                      serverPassword: tcpData.serverPassword,
                      port: tcpData.port * 1
                    })
                      .then(isPassLinkTest => {
                        this.setState({
                          isPassLinkTest,
                          isFirstTest: true,
                          Testing: false
                        })
                      })
                      .catch(() => {
                        this.setState({ Testing: false })
                      })
                  }
                }}
              >
                连接测试
              </Button>
            </div>
          </Form>
        </Modal>
      </div>
    )
  }
}

export default connect(state => ({
  state
}))(Form.create()(UserManage))
